package com.guanghua.brick.web.extend.struts;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.guanghua.brick.util.StringUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class CommaDataConvertInterceptor implements Interceptor {
	
	private static Log logger = LogFactory.getLog(CommaDataConvertInterceptor.class);
	
	public void destroy() {}

	public void init() {}

	public String intercept(ActionInvocation action) throws Exception {
		//遍历field
		Object o = action.getAction();
		logger.trace("convert comma data interceptor action:" + o);
		Field[] fs = o.getClass().getDeclaredFields();
		logger.trace("convert comma data action field length:" + fs.length);
		for (Field f:fs) {
			logger.trace("convert comma data action field name:" + f.getName());
			
			//寻找annotation
			CommaData cd = (CommaData)f.getAnnotation(CommaData.class);
			if (cd == null) continue;
			
			//寻找seter
			String setterName = getSetterName(f.getName());
			logger.trace("convert comma data find setter name:" + setterName);
			Method setter = o.getClass().getMethod(setterName, new Class[]{f.getType()});
			if (setter == null) continue;
			
			String paramName = cd.value();
			//如果param name空, 那么用field的名字作param name
			if (paramName.length() == 0) {
				paramName = f.getName();
			}
			logger.trace("convert comma data param name:" + paramName);
			
			//读取req的值
			String value = ServletActionContext.getRequest().getParameter(paramName);
			logger.trace("convert comma data param value:" + value);
			//不为空,进行赋值处理
			if (value != null && value.length() != 0) {
				String[] vs = StringUtil.stringToStringArray(value);
				
				//如果是Long[]类型，或者String[]转换
				logger.trace("comma data field type: " + f.getType());
				if (f.getType().equals(Long[].class)) {
					setter.invoke(o, new Object[]{StringUtil.stringArrayToLongArray(vs)});
				} else if (f.getType().equals(String[].class)) {
					setter.invoke(o, new Object[]{vs});
				}
			}
		}
		
		return action.invoke();
	}
	
	private String getSetterName(String fieldName) {
		return "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
	}

}
